import { ref, getCurrentInstance } from "vue";
import {
  addArticleApi,
  updateArticleApi,
  getArticleApi,
  getArticleByIdApi,
} from "../api/article_api";
import { getTimeYMDHMS } from "../utils/time";
import { useSubsetStore } from "../stores/subset";
import { useUserStore } from "../stores/user"; // 导入 useUserStore 函数，用于获取用户信息，如 token 等，用于请求接口时传递给后端验证用户身份。
import { useCode } from "./codeHook";
import type { articleData } from "../utils/interface";
import router from "../router";

export function useArticle() {
  const proxy: any = getCurrentInstance()?.proxy; // 获取消息框实例
  const { tackleCode } = useCode();
  const subsetStore = useSubsetStore();
  const userStore = useUserStore();
  // 文章ID，用于编辑文章时传递给后端
  const id = ref<number>();

  const form = ref<any>(null); // 表单数据
  const formData = (data: any) => {
    // 处理表单数据
    form.value = data; // 更新表单数据
  };

  const editors = ref<any>(null); // 富文本编辑器内容
  const editorData = (content: any) => {
    // 处理富文本编辑器内容
    editors.value = content; // 更新富文本编辑器内容
  };

  //收取cover封面
  const cover = ref();
  const coverData = (e: any) => {
    cover.value = e;
  };

  const nowMonent = ref<string>(""); // 发布时间
  //发布/保存
  const submit = (e: number) => {
    //新建的发布与保存
    if (form.value && form.value.title && !id.value) {
      if (e === 0) {
        const nowTime = new Date();
        nowMonent.value = getTimeYMDHMS(nowTime);
      }
      const request1 = {
        token: userStore.token,
        value: {
          ...form.value,
          content: editors.value,
          state: e,
          created_at: getTimeYMDHMS(new Date()),
        },
      };
      if (cover.value) {
        request1.value.cover = cover.value;
      }
      addArticleApi(request1)
        .then((res: any) => {
          // 调用接口
          if (tackleCode(res.data.code)) {
            // 处理返回结果
            if (e === 0) {
              // 保存
              proxy.$message({ type: "primary", message: "保存成功" }); // 提示消息
              router.push({
                path: "/overview",
              });
              id.value = res.data.id; // 更新文章id
              return; // 结束函数
            } else if (e === 1) {
              // 发布
              proxy.$message({ type: "primary", message: "发布成功" }); // 提示消息
              router.push({
                path: "/overview",
              });
              subsetStore.count += 1; // 更新文章数量
            }
          }
        })
        .catch((error) => {
          console.error("发布文章出错:", error);
          proxy.$message({ type: "error", message: "发布失败，请稍后重试" });
        });
    }
    //编辑的发布与保存
    else if (form.value && form.value.title && id.value) {
      // 存在id，说明保存过，更新文章
      const request2 = {
        token: userStore.token,
        id: id.value, //文章id
        value: {
          ...form.value,
          content: editors.value,
          state: e,
        },
      };
      if (cover.value) {
        request2.value.cover = cover.value;
      }
      updateArticleApi(request2).then((res: any) => {
        // 调用接口
        if (tackleCode(res.data.code)) {
          // 处理返回结果
          if (e === 0) {
            // 保存
            proxy.$message({ type: "primary", message: "保存成功" }); // 提示消息
            router.push({
              path: "/overview",
            });
            return; // 结束函数
          } else if (e === 1) {
            // 发布
            proxy.$message({ type: "primary", message: "发布成功" }); // 提示消息
            router.push({
              path: "/overview",
            });
            subsetStore.count += 1; // 更新文章数量
          }
        }
      });
    } else {
      proxy.$message({ type: "warning", message: "请输入标题" }); // 提示消息
    }
  };

  //文章列表
  const articleList = ref<articleData[]>([]);
  //文章总数
  const articlCount = ref<number>(0);
  const catArtCount = ref<number>(0);
  //获取文章
  const getArticle = (request: any) => {
    try {
      getArticleApi(request).then((res) => {
        if (tackleCode(res.data.code)) {
          articleList.value = []; // 清空文章列表
          articlCount.value = 0; // 重置文章总数
          const data = res.data.data;
          articlCount.value = data.count; // 更新文章总数
          articleList.value = [...data.result]; // 更新文章列表
          catArtCount.value = data.result.length;
        }
      });
    } catch (error) {
      console.error("获取文章失败", error);
    }
  };

  //获取文章详情
  const defaultArticle = ref<any>();
  const getArticleById = (e: number) => {
    let request = {
      token: userStore.token, // 从 userStore 中获取 token
      id: e, // 文章id
    };
    id.value = e;
    getArticleByIdApi(request).then((res: any) => {
      if (tackleCode(res.data.code)) {
        // 获取文章详情数据
        defaultArticle.value = res.data.data;
        // 处理时间格式
        defaultArticle.value.created_at = getTimeYMDHMS(
          new Date(defaultArticle.value.created_at)
        );
      }
    });
  };

  return {
    form,
    submit,
    editors,
    formData,
    nowMonent,
    editorData,
    getArticle,
    articleList,
    articlCount,
    catArtCount,
    getArticleById,
    defaultArticle,
    coverData,
  };
}
